package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.codec.Base64;
import com.atguigu.tingshu.album.config.VodConstantProperties;
import com.atguigu.tingshu.album.mapper.AlbumInfoMapper;
import com.atguigu.tingshu.album.service.VodService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.util.UploadFileUtil;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.vo.album.TrackMediaInfoVo;
import com.qcloud.vod.VodUploadClient;
import com.qcloud.vod.model.VodUploadRequest;
import com.qcloud.vod.model.VodUploadResponse;
import com.tencentcloudapi.common.AbstractModel;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.ims.v20201229.ImsClient;
import com.tencentcloudapi.ims.v20201229.models.ImageModerationRequest;
import com.tencentcloudapi.ims.v20201229.models.ImageModerationResponse;
import com.tencentcloudapi.tms.v20201229.TmsClient;
import com.tencentcloudapi.tms.v20201229.models.TextModerationRequest;
import com.tencentcloudapi.tms.v20201229.models.TextModerationResponse;
import com.tencentcloudapi.vod.v20180717.VodClient;
import com.tencentcloudapi.vod.v20180717.models.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;


@Slf4j
@Service
public class VodServiceImpl implements VodService {

    @Autowired
    private VodConstantProperties vodConstantProperties;

    @Autowired
    private Credential credential;

    /**
     * 文本审核
     *
     * @param content
     * @return
     */
    @Override
    public String scanText(String content) {
        try {
            //1.实例化要请求产品的client对象,clientProfile是可选的
            TmsClient client = new TmsClient(credential, vodConstantProperties.getRegion());
            //2.实例化一个请求对象,每个接口都会对应一个request对象
            TextModerationRequest req = new TextModerationRequest();
            //3.对审核内容进行Base64编码
            req.setContent(Base64.encode(content));
            //4.返回的resp是一个TextModerationResponse的实例，与请求对象对应
            TextModerationResponse resp = client.TextModeration(req);
            //获取审核结果建议
            if (resp != null) {
                String suggestion = resp.getSuggestion();
                return suggestion.toLowerCase();
            }
        } catch (TencentCloudSDKException e) {
            log.error("[专辑服务]文本审核异常：{}", e);
        }
        return null;
    }

    /**
     * 图片同步审核
     *
     * @param file 图片文件
     * @return
     */
    @Override
    public String scanImage(MultipartFile file) {
        try {
            //1.实例化要请求产品的client对象,clientProfile是可选的
            ImsClient client = new ImsClient(credential, vodConstantProperties.getRegion());
            //2.实例化一个请求对象,每个接口都会对应一个request对象
            ImageModerationRequest req = new ImageModerationRequest();
            //2.1 对图片进行Base64编码
            req.setFileContent(Base64.encode(file.getInputStream()));
            //3.返回的resp是一个ImageModerationResponse的实例，与请求对象对应
            ImageModerationResponse resp = client.ImageModeration(req);
            // 输出json格式的字符串回包
            if (resp != null) {
                String suggestion = resp.getSuggestion();
                return suggestion.toLowerCase();
            }
        } catch (Exception e) {
            log.error("[专辑服务]图片同步审核异常：{}", e);
        }
        return null;
    }

    @Autowired
    private AlbumInfoMapper albumInfoMapper;


    /**
     * Spring提供异步任务（开启子线程执行）
     * TODO 默认使用线程池对象：ThreadPoolTaskExecutor 存在OOM安全隐患：最大线程数跟阻塞队列都是Integer最大值
     * 异步任务审核
     *
     * @param albumInfo
     */
    @Async
    public void reviewAlbumText(AlbumInfo albumInfo) {
        log.info("{}，执行审核。", Thread.currentThread().getName());
        String suggest = this.scanText(albumInfo.getAlbumTitle() + albumInfo.getAlbumIntro());
        if (suggest.equals("pass")) {
            albumInfo.setStatus(SystemConstant.ALBUM_STATUS_PASS);
        } else {
            albumInfo.setStatus(SystemConstant.ALBUM_STATUS_NO_PASS);
        }
        albumInfoMapper.updateById(albumInfo);
    }

    /**
     * 上传音视频到点播平台
     *
     * @param file
     * @return
     */
    @Override
    public Map<String, String> uploadTrack(MultipartFile file) {
        try {
            //1.将文件保存到本地临时目录下  TODO 采用定时任务清理临时目录
            String uploadTempPath = UploadFileUtil.uploadTempPath(vodConstantProperties.getTempPath(), file);
            //2.对接腾讯点播平台完成文件上传
            VodUploadClient client = new VodUploadClient(vodConstantProperties.getSecretId(), vodConstantProperties.getSecretKey());
            VodUploadRequest request = new VodUploadRequest();
            request.setMediaFilePath(uploadTempPath);
            //TODO 未指定应用ID 使用开通点播服务后默认应用ID，如果使用新建应用ID，此处需要指定
            request.setSubAppId(vodConstantProperties.getAppId());
            VodUploadResponse response = client.upload(vodConstantProperties.getRegion(), request);
            //3.封装响应结果：文件唯一标识、文件播放地址
            if (response != null) {
                String fileId = response.getFileId();
                String mediaUrl = response.getMediaUrl();
                Map<String, String> map = new HashMap<>();
                map.put("mediaFileId", fileId);
                map.put("mediaUrl", mediaUrl);
                return map;
            }
            return null;
        } catch (Exception e) {
            log.error("[专辑服务]上传音视频到点播平台异常：{}", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 调用点播平台获取音频文件详情得到：时长、大小、类型
     *
     * @param mediaFileId
     * @return
     */
    @Override
    public TrackMediaInfoVo getMediaInfo(String mediaFileId) {
        try {
            //1.实例化要请求产品的client对象,clientProfile是可选的
            VodClient client = new VodClient(credential, "");
            //2.实例化一个请求对象,每个接口都会对应一个request对象
            DescribeMediaInfosRequest req = new DescribeMediaInfosRequest();
            req.setSubAppId(vodConstantProperties.getAppId());
            String[] fileIds1 = {mediaFileId};
            req.setFileIds(fileIds1);
            //3.返回的resp是一个DescribeMediaInfosResponse的实例，与请求对象对应
            DescribeMediaInfosResponse resp = client.DescribeMediaInfos(req);
            //4.从响应对象获取音频详情信息
            if (resp != null && resp.getMediaInfoSet() != null) {
                MediaInfo[] mediaInfoSet = resp.getMediaInfoSet();
                MediaInfo mediaInfo = mediaInfoSet[0];
                //4.1 从基本信息对象获取分类
                MediaBasicInfo basicInfo = mediaInfo.getBasicInfo();
                //4.1 从元信息对象获取时长、大小
                MediaMetaData metaData = mediaInfo.getMetaData();
                //4.3 封装结果
                TrackMediaInfoVo trackMediaInfoVo = new TrackMediaInfoVo();
                trackMediaInfoVo.setType(basicInfo.getType());
                trackMediaInfoVo.setSize(metaData.getSize());
                trackMediaInfoVo.setDuration(metaData.getAudioDuration());
                return trackMediaInfoVo;
            }
            System.out.println(AbstractModel.toJsonString(resp));
        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
        }
        return null;
    }

    /**
     * 从点播平台删除音频文件
     *
     * @param mediaFileId
     */
    @Async
    @Override
    public void deleteMedia(String mediaFileId) {
        try {
            log.info("删除音频文件线程：{}", Thread.currentThread().getName());
            //1.实例化要请求产品的client对象,clientProfile是可选的
            VodClient client = new VodClient(credential, "");
            //2.实例化一个请求对象,每个接口都会对应一个request对象
            DeleteMediaRequest req = new DeleteMediaRequest();
            req.setFileId(mediaFileId);
            req.setSubAppId(vodConstantProperties.getAppId());
            //3.返回的resp是一个DeleteMediaResponse的实例，与请求对象对应
            client.DeleteMedia(req);
        } catch (Exception e) {
            log.error("[专辑服务]从点播平台删除音频文件异常：{}", e);
        }
    }

    /**
     * 发起音视频审核任务
     *
     * @param mediaFileId 音频文件ID
     * @return 审核任务ID
     */
    @Override
    public String startReviewTask(String mediaFileId) {
        try {
            //1.实例化要请求产品的client对象,clientProfile是可选的
            VodClient client = new VodClient(credential, "");
            //2.实例化一个请求对象,每个接口都会对应一个request对象
            ReviewAudioVideoRequest req = new ReviewAudioVideoRequest();
            req.setFileId(mediaFileId);
            req.setSubAppId(vodConstantProperties.getAppId());
            //3.返回的resp是一个ReviewAudioVideoResponse的实例，与请求对象对应
            ReviewAudioVideoResponse resp = client.ReviewAudioVideo(req);
            if (resp != null) {
                return resp.getTaskId();
            }
        } catch (TencentCloudSDKException e) {
            log.error("[专辑服务]发起音视频审核任务异常：{}", e);
        }
        return null;
    }

    /**
     * 根据审核任务ID 查询审核结果
     * @param reviewTaskId
     * @return
     */
    @Override
    public String getReviewTaskResult(String reviewTaskId) {
        try{
            //1.实例化要请求产品的client对象,clientProfile是可选的
            VodClient client = new VodClient(credential, "");
            //2.实例化一个请求对象,每个接口都会对应一个request对象
            DescribeTaskDetailRequest req = new DescribeTaskDetailRequest();
            req.setTaskId(reviewTaskId);
            req.setSubAppId(vodConstantProperties.getAppId());
            //3.返回的resp是一个DescribeTaskDetailResponse的实例，与请求对象对应
            DescribeTaskDetailResponse resp = client.DescribeTaskDetail(req);
            //4.解析任务详情结果
            if(resp!=null){
                String taskType = resp.getTaskType();
                if("ReviewAudioVideo".equals(taskType)){
                    ReviewAudioVideoTask reviewAudioVideoTask = resp.getReviewAudioVideoTask();
                    if("FINISH".equals(reviewAudioVideoTask.getStatus())){
                        ReviewAudioVideoTaskOutput output = reviewAudioVideoTask.getOutput();
                        if(output!=null){
                            //获取建议结果
                            return output.getSuggestion().toLowerCase();
                        }
                    }
                }
            }
        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
        }
        return null;
    }

}
